package cn.acac.yygh.user.service.impl;

import cn.acac.yygh.enums.AuthStatusEnum;
import cn.acac.yygh.enums.StatusEnum;
import cn.acac.yygh.exception.MyException;
import cn.acac.yygh.model.acl.User;
import cn.acac.yygh.model.user.Patient;
import cn.acac.yygh.model.user.UserInfo;
import cn.acac.yygh.user.mapper.PatientMapper;
import cn.acac.yygh.user.mapper.UserInfoMapper;
import cn.acac.yygh.user.service.PatientService;
import cn.acac.yygh.user.service.UserInfoService;
import cn.acac.yygh.utils.JwtHelper;
import cn.acac.yygh.vo.user.LoginVo;
import cn.acac.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl
        extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private PatientService patientService;

    /**
     * 用户登录模块
     *
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1.获取用户手机和验证码信息
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.进行非空判断
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new MyException(50000, "手机号或验证码不正确！");
        }
        //3.对验证码做进一步确认
        // 获取redis中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            throw new MyException(50000, "验证码错误！");
        }
        //4.判断是手机登录还是微信登录
        // 根据手机号去数据库中查询
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        UserInfo userInfo = null;
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            // 为空代表手机登录
            queryWrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(queryWrapper);
            // 判断是否为空
            if (StringUtils.isEmpty(userInfo)) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                // 将数据插入数据库
                baseMapper.insert(userInfo);
            }
        } else {
            // 微信登录
            queryWrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(queryWrapper);
            // 判断userInfo1是否为空
            if (StringUtils.isEmpty(userInfo)) {
                // 代表用户第一次就是用微信登录了
                QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("openid", openid);
                userInfo = baseMapper.selectOne(queryWrapper1);
                userInfo.setPhone(phone);
                baseMapper.updateById(userInfo);
            } else {
                // 代表用户不是第一次使用微信登录了
                QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("openid", openid);
                UserInfo userInfo2 = baseMapper.selectOne(queryWrapper1);
                userInfo.setNickName(userInfo2.getNickName());
                userInfo.setOpenid(userInfo2.getOpenid());
                // 将信息更新到手机信息中
                baseMapper.updateById(userInfo);
                // 将数据库的微信登录信息删除
                baseMapper.deleteById(userInfo2.getId());
            }
        }

        //5.验证用户的status状态
        if (userInfo.getStatus() == 0) {
            throw new MyException(50000, "用户已被锁定！");
        }
        //6.返回用户的信息
        Map<String, Object> userInfoMap = new HashMap<>();
        String name = null;
        // 进行一系列判断
        if (!StringUtils.isEmpty(userInfo.getName())) {
            name = userInfo.getName();
            userInfoMap.put("name", name);
        }
        if (!StringUtils.isEmpty(userInfo.getPhone())) {
            name = userInfo.getPhone();
            userInfoMap.put("name", name);
        }
        if (!StringUtils.isEmpty(userInfo.getNickName())) {
            name = userInfo.getNickName();
            userInfoMap.put("name", name);
        }
        // 7.token的认证
        // 生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        userInfoMap.put("token", token);
        return userInfoMap;
    }

    /**
     * 根据openid查询用户信息
     *
     * @param openid
     * @return
     */
    @Override
    public UserInfo findUserInfoByOpenid(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    /**
     * 根据userId获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInfo getUserInfo(Long userId) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        return userInfo;
    }

    /**
     * 根据条件查询UserInfo的信息，并进行分页
     *
     * @param pageNum
     * @param pageSize
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public Page<UserInfo> findPageAll(Integer pageNum, Integer pageSize, UserInfoQueryVo userInfoQueryVo) {
        // 设置分页条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userInfoQueryVo.getKeyword())) {
            queryWrapper.like("name", userInfoQueryVo.getKeyword()).or().eq("phone", userInfoQueryVo.getKeyword());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getAuthStatus())) {
            queryWrapper.eq("auth_status", userInfoQueryVo.getAuthStatus());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeBegin())) {
            queryWrapper.ge("create_time", userInfoQueryVo.getCreateTimeBegin());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeEnd())) {
            queryWrapper.le("create_time", userInfoQueryVo.getCreateTimeEnd());
        }
        // 添加分页信息
        Page<UserInfo> page = new Page<>(pageNum, pageSize);
        Page<UserInfo> userInfoPage = baseMapper.selectPage(page, queryWrapper);
        userInfoPage.getRecords().stream().forEach(item -> {
            this.changeUserInfo(item);
        });
        return userInfoPage;
    }

    /**
     * 根据用户的id修改用户的状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        if(status == 0 || status == 1){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 根据id查询用户信息和用户下所有的就诊人信息
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> showUserInfo(Long id) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        QueryWrapper<Patient> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id",id);
        List<Patient> patientList = patientService.selectList(queryWrapper1);

        Map<String,Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;

    }

    /**
     * 给用户添加响应的编号文字
     *
     * @param userInfo
     */
    private void changeUserInfo(UserInfo userInfo) {
        userInfo.getParam().put("statusString", StatusEnum.findStatusStringByStatus(userInfo.getStatus()));
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
    }

}
